using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;

namespace FriendlyURLsForListItemsSP2013.Features.Friendly_URL_for_List_Items_Site_Assets_Feature
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("24de3d26-bbbc-43d7-b21c-7056eded20dc")]
    public class Friendly_URL_for_List_Items_Site_Assets_FeatureEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            if (!(properties.Feature.Parent is SPSite)) return;
            var site = properties.Feature.Parent as SPSite;

            var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().FullName;
            const string className = "FriendlyURLsForListItemsSP2013.BlogPostAddedOrUpdatedEventReceiver";
            var contentType = site.RootWeb.ContentTypes[new SPContentTypeId("0x011000E831A1F5EC3A413D853C724DCDD94D4F")];
            if (contentType == null) return;

            // add the event receivers to the content type, then update.
            AddEventReceiverToContentType(className, contentType, assemblyName, SPEventReceiverType.ItemAdded,
                                          SPEventReceiverSynchronization.Asynchronous);
            AddEventReceiverToContentType(className, contentType, assemblyName, SPEventReceiverType.ItemUpdated,
                                          SPEventReceiverSynchronization.Asynchronous);
            contentType.Update();
        }

        /// <summary>
        /// Bind specified event received to specified content type
        /// </summary>
        /// <param name="className"></param>
        /// <param name="contentType"></param>
        /// <param name="assemblyName"></param>
        /// <param name="eventReceiverType"></param>
        /// <param name="eventReceiverSynchronization"></param>
        protected static void AddEventReceiverToContentType(string className,
                                                            SPContentType contentType,
                                                            string assemblyName,
                                                            SPEventReceiverType eventReceiverType,
                                                            SPEventReceiverSynchronization eventReceiverSynchronization)
        {
            if (className == null) throw new ArgumentNullException("className");
            if (contentType == null) throw new ArgumentNullException("contentType");
            if (assemblyName == null) throw new ArgumentNullException("assemblyName");

            // remove any previous instances of this event receiver (Compare by class name since previous assembly version should be removed)
            if (contentType.EventReceivers.Count > 0)
            {
                for (var i = (contentType.EventReceivers.Count - 1); i >= 0; i--)
                {
                    // normally this would be unnecessary, however if there are duplicate event receiver definitions (as there will mostly likely be
                    //          if something went wrong), deleting 1 event receivers may actually delete more than 1.
                    if ((contentType.EventReceivers.Count - 1) < i) continue;

                    // ok, we're at a valid index, check if we've found the current class definition.
                    if (contentType.EventReceivers[i].Class.ToLower().Trim() == className.ToLower().Trim())
                    {
                        contentType.EventReceivers[i].Delete();
                    }
                }
                contentType.Update();
            }

            var eventReceiver = contentType.EventReceivers.Add();
            eventReceiver.Synchronization = eventReceiverSynchronization;
            eventReceiver.Type = eventReceiverType;
            eventReceiver.Assembly = assemblyName;
            eventReceiver.Class = className;

            eventReceiver.Update();
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
